<?php

namespace Frieza\Modules\Position\Controllers;

use Doraemon\service\Popups\PopupsApi;
use Doraemon\service\position\PositionModule;
use Doraemon\service\position\UserProfileModule\Action;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;


class TabPopupsController extends BaseController
{
    use BaseTrait;

    public function saveModule(Request $request, $baseInfoId)
    {
        $data = $request->all();
        $base = $request->input('base', []);
        $rules = $request->input('rules', []);
        $popupsData = $request->input('popups', []);
        $id = $base['id'] ?? 0;
        $pos = $base['pos'] ?? 0;
        $copy_id = $base['copy_id'] ?? 0;
        $img_size = $rules['img_size'] ?? 0;
        $pic = $popupsData['bgPic'] ?? '';
        if (empty($pic)) throw new \Exception('图片必须上传');
        if (($id > 0 || $copy_id > 0) && $img_size == 0) {

        } else {
            $this->rulesValid($rules);
        }
        if ($pos == 1) {
            $userProfile = $data['user_profile'] ?? [];
            $is_all = $userProfile['action_all'];
            if (!in_array($is_all, [Action::PART_DAY, Action::PART_7DAYS, Action::PART_ONCE])) {
                throw new \Exception('展示方式限制[持续可见,单次启动App加载]');
            }
        }

        if ($id == 0) unset($popupsData['id']);

        PopupsApi::savePopups($popupsData, $baseInfoId);
    }

    public function extendList(Grid $grid)
    {

        $grid->column('pos', '展示位置')->width(100)->using($this->posOptions());
        $grid->column('img_url', '弹窗主图')->image("", 100);
//        $grid->column('linkPreview', '弹窗配置预览')->linkPreview();
    }

    private function posOptions()
    {
        $options = PositionModule::ADM_APP_TAB_MAP;
        unset($options[PositionModule::APP_TAB1]);
        return $options;
    }

    public function defaultBaseInfo(Request $request)
    {
        $response = parent::defaultBaseInfo($request);

        $response['pos'] = $response['pos'] ?: 2;

        return $response;
    }

    public function extendDefaultBaseInfo()
    {
        return [
            'popups' => [
                'type' => \Doraemon\pockets\constInterface\PopupServiceConf::STYLE_FLOATING
            ],
        ];
    }

    public function defaultUserProfile()
    {
        return [
            'action_all' => Action::PART_DAY,
            'action' => [1],
        ];
    }

    public function beforeTitleForm(Form $form)
    {
        $form->radio('base.pos', '展示位置')
            ->options($this->posOptions())
            ->required();
    }

    public function beforeLinkForm(Form $form)
    {
        $form->customPopups('popups', '弹窗配置', $form, $this->imgHelp());
    }

}


